<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <el-form ref="queryForm" :model="queryParams" :inline="true">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item prop="name" label="教师名称">
                <el-input
                  v-model="queryParams.name"
                  placeholder="请输入教师名称"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="授课类型" prop="teaching_type">
                <el-select
                  v-model="queryParams.teaching_type"
                  placeholder="请选择"
                  clearable
                  size="small"
                >
                  <el-option
                    v-for="dict in teachingTypeOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="任教科目" prop="teaching_subject">
                <el-select
                  v-model="queryParams.teaching_subject"
                  placeholder="请选择"
                  clearable
                  size="small"
                >
                  <el-option
                    v-for="dict in subjectOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <el-row :gutter="20">
          <el-col :span="5" :xs="24">
            <div class="head-container">
              <el-tree
                ref="tree"
                :data="deptOptions"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                default-expand-all
                @node-click="handleNodeClick"
              />
            </div>
          </el-col>
          <el-col :span="19">
            <el-row :gutter="10" class="mb10" style="float:right">
              <el-col :span="1.5">
                <!-- v-permisaction="['admin:sysUser:add']" -->
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="multiple"
                  @click="handleDelete"
                >删除</el-button>
              </el-col>
            </el-row>
            <el-table
              v-loading="loading"
              :data="userList"
              border
              @selection-change="handleSelectionChange"
              @sort-change="handleSortChang"
            >
              <el-table-column type="selection" width="45" align="center" />
              <el-table-column label="教师名称" width="200" prop="name" :show-overflow-tooltip="true" />
              <el-table-column label="手机号" prop="tel_phone" />
              <el-table-column label="任教科目" prop="teaching_subject" :show-overflow-tooltip="true" />
              <el-table-column label="授课类型" prop="teaching_type" :show-overflow-tooltip="true" />
              <el-table-column label="是否置顶" width="80">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.is_top"
                    :active-value="1"
                    :inactive-value="-1"
                    @change="handleStatusChange(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                width="180"
                fixed="right"
                align="center"
                class-name="small-padding fixed-width"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-view"
                    @click="handleView(scope.row)"
                  >查看</el-button>
                  <el-button
                    size="mini"
                    :disabled="!multiple && single"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                  >修改</el-button>
                  <el-button
                    :disabled="!multiple && single"
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageIndex"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </el-row>
      </el-card>

      <el-drawer
        ref="drawer"
        :title="title"
        :visible.sync="open"
        direction="rtl"
        custom-class="demo-drawer"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="教师名称" prop="user_id">
                <el-select
                  v-model="form.user_id"
                  remote
                  filterable
                  placeholder="请选择教师"
                  :remote-method="remoteMethod"
                  :loading="selectload"
                  style="width: 100%"
                  @change="userChange"
                >
                  <el-option
                    v-for="(item, index) in userArray"
                    :key="index"
                    :label="item.nick_name"
                    :value="item.user_id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="手机号码" prop="tel_phone">
                <el-input v-model="form.tel_phone" placeholder="请输入手机号码" maxlength="11" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="教师工号" prop="teacher_number">
                <el-input v-model="form.teacher_number" placeholder="请输入教师工号" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="毕业院校" prop="graduated_from">
                <el-input v-model="form.graduated_from" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="任教科目" prop="teaching_subject">
                <el-select
                  v-model="form.teaching_subject"
                  style="width: 100%"
                  placeholder="请选择"
                  size="small"
                >
                  <el-option
                    v-for="dict in subjectOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="授课类型" prop="teaching_type">
                <el-select
                  v-model="form.teaching_type"
                  style="width: 100%"
                  placeholder="请选择"
                  size="small"
                >
                  <el-option
                    v-for="dict in teachingTypeOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="所属部门" prop="dept_id">
                <treeselect
                  v-model="form.dept_id"
                  :options="deptOptions"
                  :normalizer="normalizer"
                  placeholder="选择部门"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="所属教学点" prop="teaching_point_id">
                <el-select
                  v-model="form.teaching_point_id"
                  remote
                  filterable
                  placeholder="请选择教学点"
                  :remote-method="remoteSchool"
                  :loading="selectload"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in schoolList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="教师画像" prop="avatar">
                <el-upload
                  :headers="headers"
                  :action="$uploadUrl"
                  class="avatar-uploader"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :on-success="uploadSuccess"
                >
                  <el-image v-if="avatarImg" :src="getMediaUrl(avatarImg)" class="upload-image" />
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="置顶展示" prop="is_top">
                <el-switch
                  v-model="isTop"
                  :active-value="1"
                  :inactive-value="-1"
                  @change="handleSwitchChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="标签">
                <el-tag
                  v-for="tag in dynamicTags"
                  :key="tag"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag)"
                >{{ tag }}</el-tag>
                <el-input
                  v-if="inputVisible"
                  ref="saveTagInput"
                  v-model="inputValue"
                  size="small"
                  class="input-new-tag"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm"
                />
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新增标签</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="教学特点" prop="teaching_characteristic">
                <el-input
                  v-model="form.teaching_characteristic"
                  :rows="4"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="教学经历" prop="teaching_experience">
                <el-input
                  v-model="form.teaching_experience"
                  :rows="4"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="教师简介" prop="introduction">
                <el-input
                  v-model="form.introduction"
                  :rows="4"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-drawer>

      <el-drawer
        :with-header="false"
        :visible.sync="visible"
        custom-class="demo-drawer"
        @closed="dynamicTags = []"
      >
        <el-card class="box-card">
          <div>
            <div class="text-center">
              <el-avatar shape="circle" :size="100" :src="$host + teacher.avatar" />
            </div>
            <ul class="list-group list-group-striped">
              <li class="list-group-item">
                <svg-icon icon-class="user" />教师名称
                <div class="pull-right">{{ teacher.name }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="phone" />手机号码
                <div class="pull-right">{{ teacher.tel_phone }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="star" />毕业院校
                <div class="pull-right">{{ teacher.graduated_from }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="rate" />任教科目
                <div class="pull-right">{{ teacher.teaching_subject }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="safety" />授课类型
                <div class="pull-right">{{ teacher.teaching_type }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="signature" />教学特点
                <div class="pull-right">{{ teacher.teaching_characteristic }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="tree" />教学经历
                <div class="pull-right">{{ teacher.teaching_experience }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="peoples" />教师简介
                <div class="pull-right">{{ teacher.introduction }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="operators" />标签
                <div class="pull-right">
                  <el-tag
                    v-for="tag in dynamicTags"
                    :key="tag"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)"
                  >{{ tag }}</el-tag>
                </div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="date" />创建日期
                <div class="pull-right">{{ teacher.createdAt }}</div>
              </li>
            </ul>
          </div>
        </el-card>
      </el-drawer>
    </template>
  </BasicLayout>
</template>

<script>
import { importTemplate } from '@/api/admin/sys-user'
import { getToken } from '@/utils/auth'
import { getSubject, getUserList } from '@/api/admin/sys-course'
import { getSchoolList } from '@/api/admin/sys-academy'
import {
  listTeacher,
  addTeacher,
  delTeacher,
  updateTeacher,
  updateStatusTeacher
} from '@/api/admin/sys-teacher'
import { treeselect } from '@/api/admin/sys-dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'SysTeacherManage',
  components: { Treeselect },
  data() {
    return {
      headers: { Authorization: 'Bearer ' + getToken() },
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      // 遮罩层
      loading: true,
      visible: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 表单参数
      form: {
        avatar: null
      },
      avatarImg: null,
      teacher: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      isTop: 1,
      subjectOptions: [],
      teachingTypeOptions: [
        {
          label: '网课',
          value: '网课'
        },
        {
          label: '面授',
          value: '面授'
        }
      ],
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        name: undefined,
        tel_phone: undefined
        // status: undefined
      },
      // 表单校验
      rules: {
        user_id: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        teaching_subject: [
          { required: true, message: '任教科目不能为空', trigger: 'blur' }
        ],
        teacher_number: [
          { required: true, message: '教师编号不能为空', trigger: 'blur' }
        ],
        avatar: [{ required: true, message: '请上传头像', trigger: 'blur' }],
        introduction: [
          { required: true, message: '简介不能为空', trigger: 'blur' }
        ],
        teaching_type: [
          { required: true, message: '类型不能为空', trigger: 'blur' }
        ],
        graduated_from: [
          { required: true, message: '毕业院校不能为空', trigger: 'blur' }
        ],
        teaching_experience: [
          { required: true, message: '教学经历不能为空', trigger: 'blur' }
        ],
        teaching_characteristic: [
          { required: true, message: '教学特点不能为空', trigger: 'blur' }
        ],
        dept_id: [
          { required: true, message: '所属部门不能为空', trigger: 'blur' }
        ],
        tel_phone: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      },
      userArray: [],
      selectload: false,
      schoolParams: {
        pageIndex: 1,
        pageSize: 1000,
        name: undefined
      },
      schoolList: []
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getSubject()
    this.getTreeselect()
    this.getUserList()
    this.getSchoolList()
  },
  methods: {
    getList() {
      this.loading = true
      listTeacher(this.queryParams).then(response => {
        this.userList = response.data.list
        this.total = response.data.count
        this.loading = false
      })
    },
    getUserList() {
      getUserList().then(res => {
        this.userArray = res?.data
      })
    },
    getSchoolList() {
      getSchoolList(this.schoolParams).then(res => {
        this.schoolList = res?.data?.list || []
        this.selectload = false
      })
    },
    handleSwitchChange(e) {
      this.form.is_top = e
      this.isTop = e
    },
    getSubject() {
      getSubject().then(response => {
        this.subjectOptions =
          response.data?.map(i => ({
            label: i.name,
            value: i.name
          })) || []
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = [
          {
            id: 0,
            label: '重庆拓为',
            children: response.data
          }
        ]
        // this.queryParams.deptId = response.data?.[0].id
        this.getList()
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.getList()
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      }
    },
    /** 排序回调函数 */
    handleSortChang(column, prop, order) {
      prop = column.prop
      order = column.order
      if (this.order !== '' && this.order !== prop + 'Order') {
        this.queryParams[this.order] = undefined
      }
      if (order === 'descending') {
        this.queryParams[prop + 'Order'] = 'desc'
        this.order = prop + 'Order'
      } else if (order === 'ascending') {
        this.queryParams[prop + 'Order'] = 'asc'
        this.order = prop + 'Order'
      } else {
        this.queryParams[prop + 'Order'] = undefined
      }
      this.getList()
    },
    // 用户状态修改
    handleStatusChange(row) {
      const text = row.is_top === 1 ? '置顶' : '取消置顶'
      this.$confirm('确认要"' + text + '""' + row.name + '"吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return updateStatusTeacher({
            id: row.id,
            is_top: row.is_top
          })
        })
        .then(() => {
          this.msgSuccess(text + '成功')
          this.getList()
        })
        .catch(function() {
          row.is_top = row.is_top === 1 ? -1 : 1
        })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
      this.avatarImg = null
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleView(row) {
      this.visible = true
      this.teacher = row
      this.dynamicTags = row.label?.split(',').filter(i => 1)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加教师'
    },
    userChange(data) {
      const userData = this.userArray?.find(item => item.user_id === data)
      this.form.tel_phone = userData?.phone
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.dynamicTags = row.label?.split(',').filter(i => i)
      this.isTop = row.is_top
      this.avatarImg = row.avatar
      this.form = {
        id: row.id,
        name: row.name,
        tel_phone: row.tel_phone,
        teaching_subject: row.teaching_subject,
        teaching_type: row.teaching_type,
        avatar: row.avatar,
        is_top: row.is_top,
        graduated_from: row.graduated_from,
        teaching_experience: row.teaching_experience,
        teaching_characteristic: row.teaching_characteristic,
        introduction: row.introduction,
        user_id: row.user_id,
        dept_id: row?.dept_id,
        teacher_number: row?.teacher_number,
        teaching_point_id: row?.teaching_point_id || null
      }
      this.open = true
      this.title = '修改教师'
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const userData = this.userArray?.find(
            item => item.user_id === this.form.user_id
          )
          this.form.name = userData?.nick_name
          // const deptText = this.location4?.find(item => item =>
          //   item.dept_id === this.form.dept_id
          // );
          // this.form.dept_id_text = deptText?.dept_name;
          if (this.form.id !== undefined) {
            this.form.label = this.dynamicTags.toString()
            updateTeacher(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.open = false
                this.getList()
                this.dynamicTags = []
              } else {
                this.msgError(response.msg)
              }
            })
            return
          }
          this.form.label = this.dynamicTags.toString()
          addTeacher(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(response.msg)
              this.open = false
              this.getList()
              this.dynamicTags = []
            } else {
              this.msgError(response.msg)
            }
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = (row.id && [row.id]) || this.ids
      this.$confirm('是否确认删除该数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return delTeacher({ ids })
        })
        .then(response => {
          if (response.code === 200) {
            this.msgSuccess(response.msg)
            this.open = false
            this.getList()
          } else {
            this.msgError(response.msg)
          }
        })
        .catch(function() {})
    },
    uploadSuccess(res) {
      this.form.avatar = res.data.full_path
      this.avatarImg = res.data.full_path
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2.0
      const isJPG = file.type.indexOf('image/') === -1
      if (isJPG) {
        this.$message.error(
          '文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件'
        )
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2M!')
      }
      return !isJPG && isLt2M
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '用户导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg)
      })
    },
    remoteMethod(query) {
      if (query !== '') {
        this.selectload = true
        getUserList({ nick_name: query }).then(res => {
          this.userArray = res?.data || []
          this.selectload = false
        })
      } else {
        this.userArray = []
      }
    },
    remoteSchool(data) {
      if (data !== '') {
        this.selectload = true
        this.schoolParams.name = data
        this.getSchoolList()
      } else {
        this.schoolList = []
      }
    }
  }
}
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.list-group-item {
  padding: 18px 0;
}
.svg-icon {
  margin-right: 5px;
}
</style>
